package com.stylefeng.guns.core.util.excel;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * excel导入组件 .xls后缀
 *
 * @author carloszhang
 */
public abstract class AnalyzeExcelXlsComponent<T> {

    private static final int DEFAULT_ONSET_ROW = 1;

    private static final int DEFAULT_VALUE = 0;

    public List<T> analyzeExcel(InputStream is) throws Exception {
        return analyzeExcel(is, DEFAULT_ONSET_ROW);
    }

    public List<T> analyzeExcel(InputStream is, int onsetRow) throws Exception {

        HSSFWorkbook workbook = new HSSFWorkbook(is);
        List<T> datas = new ArrayList<T>();
        HSSFSheet sheet = workbook.getSheetAt(DEFAULT_VALUE);
        if (sheet == null) {
            return null;
        }
        for (int rowNum = onsetRow; rowNum <= sheet.getLastRowNum(); rowNum++) {
            HSSFRow row = sheet.getRow(rowNum);
            if (row == null || StringUtils.isBlank(String.valueOf(row.getCell(DEFAULT_VALUE)))) {
                continue;
            }
            T t = buildData(row);
            if(t != null){
                datas.add(t);
            }
        }
        return datas;

    }

    protected abstract T buildData(HSSFRow row);

    protected HSSFCell getCell(HSSFRow row, int onsetCell) {
        return row.getCell(onsetCell);
    }

    /**
     * 这个待完善数据类型
     */
    protected String getValue(HSSFCell cell) {
        try {
            return StringUtils.trimToNull(String.valueOf(cell.getStringCellValue()));
        } catch (Exception e) {
            return StringUtils.trimToNull(String.valueOf(new BigDecimal(cell.getNumericCellValue()).intValue()));
        }

    }

    protected String getValueNum(HSSFCell cell) {
        return StringUtils.trimToNull(String.valueOf(cell.getNumericCellValue()));
    }
}
